import React, { PureComponent } from 'react';
import { Form, Input, Select, Modal, Upload, Icon, message, Row, Col, TreeSelect} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
const tree_icon = {
  all: require("@/assets/org_all.png"),
  company: require("@/assets/org_company.png"),
  team: require("@/assets/org_team.gif"),
}
class CustomizedForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      treeData:{},
      TreeValue: {}
    };
  }
  componentDidMount(){
    const { modalValues, orgMenuList} = this.props
    if (modalValues.photo && modalValues.photo.length) {
      const data = [{
        uid: '-1',
        name: 'xxx.png',
        status: 'done',
        imageUrl: modalValues.photo,
        url: "http://39.104.84.146:8888/" + modalValues.photo
      }]
      this.setState({
        fileList: data
      })
    } else {
      this.setState({
        fileList: []
      })
    }
    this.setState({
      treeData: orgMenuList,
      TreeValue: {
        orgId: modalValues.orgId,
        orgName: modalValues.orgName
      }
    })
  }
  okHandle = () => {
    const { form, handleSubmit, modalValues } = this.props;
    const { fileList,TreeValue} = this.state
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      fieldsValue.id = modalValues.id;
      if (fileList.length){
        if (fileList[0].response){
          fieldsValue.photo = fileList[0].response.imagePath
        }else{
          fieldsValue.photo = fileList[0].imageUrl
        }
      }else{
        fieldsValue.photo = ""
      }
      // form.resetFields();
      const data = {
        ...fieldsValue,
        ...TreeValue
      }
      handleSubmit(data);
      console.log(data)
    });
  };
  /**
   * 上传司机图片
   */
  handleCancel = () => this.setState({ previewVisible: false })
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  handleChange = ({ fileList, file }) => {
    if (file.status == "done"){
      message.success("上传成功！")
    } else if (file.status == "error"){
      message.warning("上传失败")
    }
    console.log("fileList", fileList)
    return this.setState({ fileList })
  }
  // 上传司机图片***end****
  /**
   * 异步数
   */
  onTreeChange = (value, label, extra) => {
    var data = {
      orgName: label[0],
      orgId: value,
    }
    this.setState({
      TreeValue: data
    })
  }
  onLoadData = treeNode => new Promise((resolve) => {
    const { dispatch } = this.props
    if (treeNode.props.children) {
      resolve();
      return;
    }
    dispatch({
      type: "driver/fetchOrganize",
      payload: {
        menuId: treeNode.props.dataRef.id
      },
      callback: (res) => {
        treeNode.props.dataRef.children = res.orgMenuList
        this.setState({
          treeData: [...this.state.treeData],
        });
        resolve();
      }
    })
  })
  renderTreeNodes = data => data.map((item) => {
    if (item.children) {
      return (
        <TreeNode {...item} title={item.name} key={item.id} dataRef={item} icon={<img src={item.orgType == 1 ? tree_icon.company : tree_icon.team} />}>
          {this.renderTreeNodes(item.children)}
        </TreeNode>
      );
    }
    if (Object.keys(item).length == 0) return
    return <TreeNode {...item} title={item.name} key={item.id} dataRef={item} isLeaf={item.leaf ? false : true} icon={<img src={item.orgType == 1 ? tree_icon.company : tree_icon.team} />} />;

  })
  render() {
    const { modalVisible, modalValues, handleModalVisible, form } = this.props;
    const { previewVisible, previewImage, fileList, treeData } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <Modal
        destroyOnClose //关闭时销毁 Modal 里的子元素
        title={Object.keys(modalValues).length ? '修改司机信息' : '添加司机信息'}
        visible={modalVisible}
        onOk={this.okHandle}
        maskClosable={false}
        width={900}
        onCancel={() => handleModalVisible()}
      >
        <Row>
          <Col span={12}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="驾驶员姓名">
              {form.getFieldDecorator('driverName', {
                rules: [{ required: true, message: '请输入驾驶员姓名' }],
                initialValue: modalValues.driverName || '',
              })(<Input placeholder="请输入" autoComplete="off" />)}
            </FormItem>
          </Col>
          <Col span={12}>
            {treeData && Object.keys(treeData).length ? (
              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="所属组织">
                {form.getFieldDecorator('orgName', {
                  rules: [{ required: true, message: '请输入所属组织机构' }],
                  initialValue: modalValues.orgName || '',
                })(
                  <TreeSelect
                    // value={this.state.value}
                    showIcon={true}
                    loadData={this.onLoadData}
                    style={{ width: "100%" }}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    placeholder="Please select"
                    onChange={this.onTreeChange}
                    allowClear
                  >
                    {this.renderTreeNodes(treeData)}
                  </TreeSelect>
                )}
              </FormItem>
            ):null}
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="司机手机号">
              {form.getFieldDecorator('phoneNo', {
                rules: [{ required: true, message: '请输入司机手机号' }],
                initialValue: modalValues.phoneNo || '',
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="性别">
              {form.getFieldDecorator('sex', {
                rules: [{ required: true }],
                initialValue: Object.keys(modalValues).length ? modalValues.sex : 2,
              })(
                <Select style={{ width: '100%' }}>
                  <Option value={0}>男性</Option>
                  <Option value={1}>女性</Option>
                  <Option value={2}>未知</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="身份证号码">
              {form.getFieldDecorator('idNo', {
                rules: [{ required: true, message: '请输入身份证号码' }],
                initialValue: modalValues.idNo || '',
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="驾照类型">
              {form.getFieldDecorator('licenseType', {
                rules: [{ required: true, message: '请输入驾照类型' }],
                initialValue: modalValues.licenseType || '',
              })(<Input placeholder="请输入" />)}
            </FormItem>        
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="备注信息">
              {form.getFieldDecorator('remarks', {
                rules: [{ required: true, message: '请输入备注信息' }],
                initialValue: modalValues.remarks || '',
              })(<Input placeholder="请输入" />)}
            </FormItem>   
          </Col>
          <Col span={12}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="司机照片">
              {form.getFieldDecorator('666')(
                <Upload
                  action="http://39.104.84.146:8030/driver/uploadDriverImage"
                  listType="picture-card"
                  fileList={fileList}
                  accept="image/jpg,image/jpeg,image/png,image/bmp"
                  supportServerRender
                  withCredentials
                  onPreview={this.handlePreview}
                  onChange={this.handleChange}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
              )}
            </FormItem> 
          </Col>
        </Row>        
        <div className="clearfix">          
          <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
            <img alt="example" style={{ width: '100%' }} src={previewImage} />
          </Modal>
        </div>    
      </Modal>
    );
  }
}
const CreateForm = Form.create()(CustomizedForm);

export default CreateForm;
